package com.tianji.aigc.Service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.aigc.Service.IChatService;
import com.tianji.aigc.config.SpringAiConfig;
import com.tianji.aigc.domain.ChatSession;
import com.tianji.aigc.domain.VO.ChatEventVO;
import com.tianji.aigc.domain.dto.ChatDTO;
import com.tianji.aigc.domain.enums.ChatEventTypeEnum;
import com.tianji.aigc.mapper.ChatSessionMapper;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.concurrent.ConcurrentHashMap;
@Service
public class ChatServiceimpl  implements IChatService {
    @Autowired
    private ChatClient chatClient;
    //生成一个concretHashMap
    private static final ConcurrentHashMap<String, Boolean> chatSessionMap = new ConcurrentHashMap<>();
    @Override
    public Flux<ChatEventVO> chat(String question, String sessionId) {
        return this.chatClient.prompt()
                .system(SpringAiConfig.AI_PROMOPT)
                .user( question)
                .stream()
                .chatResponse()
                .doFirst(new Runnable() {
                             @Override
                             public void run() {
                                 chatSessionMap.put(sessionId, true);

                             }
                         }
                )
                .doOnError(throwable -> {
                    chatSessionMap.remove(sessionId);
                })
                .doOnComplete( () -> {
                    chatSessionMap.getOrDefault(sessionId, false);
                })
                .map(chatresponse -> {
                    chatresponse.getResult().getOutput().getText();
                    return ChatEventVO.builder()
                            .eventData(chatresponse.getResult().getOutput().getText())
                            .eventType(ChatEventTypeEnum.DATA.getValue())
                            .build();
                })
                .concatWith(Flux.just(ChatEventVO.builder()  // 标记输出结束
                .eventType(ChatEventTypeEnum.STOP.getValue())
                .build()));

    }

    @Override
    public void stop(String sessionId) {
        chatSessionMap.remove(sessionId);
    }
}
